<template>
  <ContentWrap :bodyStyle="{ paddingTop: '5px' }">
    <Back :backOption="backOption" />
    <div class="h-full">
      <el-form
        class="top-search"
        label-width="140px"
        :model="formData"
        ref="syncFileFormRef"
        :rules="rules"
        @submit.prevent
      >
        <el-row class="row-item" :gutter="40">
          <el-col :span="12">
            <el-form-item label="上级节点" prop="pid">
              <el-tree-select
                style="max-width: 400px; width: 100%"
                ref="treeGroupRef"
                v-model="formData.pid"
                value-key="id"
                node-key="id"
                :data="treeGroupData"
                :props="{ label: 'name' }"
                :render-after-expand="false"
                placeholder="请选择上级节点"
                check-strictly
                :default-expanded-keys="['0']"
                clearable
                @change="treeGroupChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新增文件组名称" prop="groupName" class="col-item">
              <ns-input
                style="max-width: 400px; width: 100%"
                v-model="formData.groupName"
                placeholder="请输入文件组名称"
              />
            </el-form-item>
          </el-col>
          <template v-if="formData.groupName">
            <el-col :span="12">
              <el-form-item label="归属机构" prop="deptId" class="col-item">
                <el-cascader
                  style="max-width: 400px; width: 100%"
                  ref="deptCascader"
                  v-model="formData.deptId"
                  placeholder="请选择归属机构"
                  :props="cascaderProps"
                  :options="deptList"
                  filterable
                  clearable
                  value-on-clear=""
                  :filter-method="sysFilterMethod"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="归属系统" prop="sysId" class="col-item">
                <el-cascader
                  ref="systemCascader"
                  style="max-width: 400px; width: 100%"
                  v-model="formData.sysId"
                  placeholder="请选择归属系统"
                  :props="systemCascaderProps"
                  :options="systemList"
                  filterable
                  clearable
                  value-on-clear=""
                  :filter-method="sysFilterMethod"
                />
              </el-form-item>
            </el-col>
          </template>
          <!-- <el-col :span="6" v-if="fileGroupType === 2">
            <el-form-item label="目标文件组" prop="groupId" class="col-item" ref="groupIdRef">
              <el-tree-select
                style="width: 100%"
                placeholder="请选择目标文件组"
                v-model="formData.groupId"
                value-key="id"
                node-key="id"
                :data="childGroup"
                :props="{ label: 'name' }"
                :render-after-expand="false"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-radio-group v-model="fileGroupType">
                <el-radio :label="1">新增文件组</el-radio>
                <el-radio :label="2">上传至已有文件组</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <el-row :gutter="20" class="bt-wrap">
        <!-- 左侧树 -->
        <el-col :span="4" :xs="24" v-if="pageType === '1'">
          <div class="tree-wrap"> <DataSourceTree @node-click="treeNodeClick" /> </div>
        </el-col>
        <el-col :span="pageType === '1' ? 20 : 24" :xs="24">
          <!-- 搜索 -->
          <el-form
            ref="queryFormRef"
            :model="queryParams"
            class="table-form mb-15px flex flex-wrap"
            label-width="98px"
          >
            <el-col :span="6">
              <el-form-item label="文件名称" prop="fileName">
                <ns-input
                  v-model="queryParams.fileName"
                  class="!w-full"
                  clearable
                  placeholder="请输入文件名称"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="文件类型" prop="fileType">
                <ns-input
                  v-model="queryParams.fileType"
                  class="!w-full"
                  clearable
                  placeholder="请输入文件类型"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="数据保护标准" prop="template">
                <el-select
                  v-model="queryParams.template"
                  class="!w-full"
                  clearable
                  placeholder="请选择数据保护标准"
                >
                  <el-option
                    v-for="(template, templateIndex) in templateList"
                    :key="templateIndex"
                    :label="template.dataStandardName"
                    :value="template.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="归属机构" prop="deptId">
                <el-cascader
                  v-model="queryParams.deptId"
                  clearable
                  class="!w-full"
                  placeholder="请选择归属机构"
                  :options="deptList"
                  :props="cascaderProps"
                  filterable
                  :filter-method="sysFilterMethod"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="归属系统" prop="sysId">
                <el-cascader
                  v-model="queryParams.sysId"
                  placeholder="请选择归属系统"
                  class="!w-full"
                  :props="systemCascaderProps"
                  :options="systemList"
                  filterable
                  clearable
                  :filter-method="sysFilterMethod"
              /></el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="分类" prop="classification">
                <el-cascader
                  v-model="queryParams.classification"
                  placeholder="请选择分类"
                  class="!w-full"
                  :props="classificationCascaderProps"
                  :options="classificationList"
                  filterable
                  clearable
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="分级" prop="level">
                <el-select
                  class="!w-full"
                  placeholder="请选择分级"
                  v-model="queryParams.level"
                  clearable
                >
                  <el-option
                    v-for="(level, levelIndex) in levelList"
                    :key="levelIndex"
                    :label="level.levelName"
                    :value="level.levelCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="重要程度" prop="importance">
                <el-select
                  class="!w-full"
                  placeholder="请选择重要程度"
                  v-model="queryParams.importance"
                  clearable
                >
                  <el-option label="重要数据" value="重要数据" key="1" />
                  <el-option label="公开数据" value="公开数据" key="0" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="自动分级状态" prop="autoClassStatus">
                <el-select
                  v-model="queryParams.autoClassStatus"
                  clearable
                  placeholder="请选择分级状态"
                >
                  <el-option
                    v-for="(item, index) in autoClassStatusMap"
                    :key="index"
                    :label="item[1]"
                    :value="item[0]"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否已分级">
                <el-select v-model="queryParams.isLevel" clearable placeholder="请选择是否已分级">
                  <el-option label="已分级" :value="true" />
                  <el-option label="未分级" :value="false" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="pb-20px text-right">
              <el-button @click="handleQuery">
                <Icon class="mr-5px" icon="ep:search" />
                搜索
              </el-button>
              <el-button @click="resetQuery">
                <Icon class="mr-5px" icon="ep:refresh" />
                重置
              </el-button>
            </el-col>
          </el-form>

          <div>
            <el-table ref="treeTableRef" v-loading="loading" :data="tableList" row-key="id">
              <el-table-column type="selection" width="85" />
              <el-table-column prop="fileName" label="文件名称" align="center" />
              <el-table-column prop="fileType" label="文件类型" align="center" />
              <el-table-column prop="fileSize" label="文件大小" align="center" />
              <el-table-column prop="templateName" label="数据保护标准" align="center" />
              <el-table-column prop="deptName" label="归属机构" align="center" />
              <el-table-column prop="sysName" label="归属系统" align="center" />
              <!-- <el-table-column prop="absolutePath" label="文件路径" align="center" />
              <el-table-column prop="fileFingerprint" label="哈希（sha256）" align="center" /> -->
              <el-table-column
                prop="classification"
                label="分类"
                align="center"
                :formatter="(row) => renderClassification({ row })"
              />
              <el-table-column
                prop="level"
                label="分级"
                align="center"
                :formatter="(row) => renderLevel({ row })"
              />
              <el-table-column prop="importance" label="重要程度" align="center">
                <template #default="{ row }">
                  <span>{{ row.handImportance || row.importance || '--' }}</span>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <Pagination
              v-model:limit="queryParams.pageSize"
              v-model:page="queryParams.page"
              :total="total"
              @pagination="getList"
            />
          </div>
        </el-col>
      </el-row>
      <div style="text-align: center; margin-top: 12px">
        <el-button
          type="primary"
          @click="submit"
          :loading="formLoading || disabled"
          :disabled="formLoading || disabled"
          >确定</el-button
        >
        <el-button @click="handleClose" :loading="formLoading || disabled">取消</el-button>
      </div>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { sysFilterMethod } from '@/utils/selectFilter'
import * as FileConfigApi from '@/api/infra/fileConfig'
import { dataClassificationTree } from '@/api/dataStandards/classification/index'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { levelPage } from '@/api/strategyManage/level/index'
import DataSourceTree from './DataSourceTree.vue'
import Back from '@/components/Back/index.vue'
import { useGroupTree } from '@/hooks/web/useFileTree'
import { createFileManage, createFromAsset } from '@/api/develop/file'
import { getDataBaseList as getDataBaseListRemote } from '@/api/assetList/index'
import type { FormInstance } from 'element-plus'
import { ElTreeSelect, ElTable, ElFormItem } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { useEmitt } from '@/hooks/web/useEmitt'
import { getSimpleDeptList } from '@/api/system/dept'
import { handleTree } from '@/utils/tree'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { fileTypes } from './constants'
import { autoClassStatusMap } from '@/utils/dict'

import {
  renderFinger,
  sourceRender,
  renderClassification,
  renderLevel,
  autoClassStatusRender
} from '@/utils/commonRender'

const message = useMessage() // 消息弹窗
const { emitter } = useEmitt()
const { t } = useI18n() // 国际化
const router = useRouter()
const { params } = useRoute() // 查询参数

const syncFileFormRef = ref<FormInstance>()
const treeGroupRef = ref<InstanceType<typeof ElTreeSelect>>()
const treeTableRef = ref<InstanceType<typeof ElTable>>()
const groupIdRef = ref<InstanceType<typeof ElFormItem>>()

const pageType: any = computed(() => {
  return params?.type || ''
})
// console.log('params', params.type)
const queryFormRef = ref() // 搜索的表单
const titleMap = new Map([
  ['1', '同步文件服务器'],
  ['2', '同步文件资产'],
  ['3', '同步监测平台']
])
const backOption = computed(() => {
  return {
    title: titleMap.get(pageType.value)
  }
})

const data = reactive({
  formData: {
    pid: '0',
    groupName: '',
    sysId: '',
    deptId: ''
    // groupId: ''
  },

  fileGroupType: pageType.value === '3' ? 3 : 1, //1:文件，文件服务器，3：监测平台
  childGroup: []
})
const isRequired = computed(() => {
  return !formData.value.deptId && !formData.value.sysId
})

const rules = computed(() => ({
  pid: [{ required: true, message: '请选择上级节点', rigger: ['blur', 'change'] }],
  groupName: [
    { required: data.formData.pid == '0', message: '请输入文件组名称', rigger: ['blur', 'change'] }
  ],
  groupId: [{ required: true, message: '请选择目标文件组', rigger: ['blur', 'change'] }],
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }]
}))
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})

const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'text',
  value: 'id',
  children: 'children',
  emitPath: false
})

const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const formLoading = ref(false)

const { treeGroupData, reFreshTreeData } = useGroupTree()

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  dataType: 'file',
  isSingle: pageType.value === '1' ? '' : 'true',
  source: pageType.value === '3' ? '5' : '',
  parentId: pageType.value === '1' ? '-1' : '',
  fileName: '',
  fileType: '',
  level: '',
  importance: '',
  isLevel: '',
  template: '',
  deptId: '',
  classification: '',
  sysId: '',
  autoClassStatus: ''
})
const total = ref(0) // 列表的总页数
const loading = ref(false) // 列表的加载中
const tableList = ref([]) // 列表的数据
// let domain

const { formData, fileGroupType, childGroup } = toRefs(data)

const disabled = ref(false)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const { count, data } = await getDataBaseListRemote(toRaw(queryParams))
    total.value = count
    tableList.value = data
  } finally {
    loading.value = false
  }
}

function treeGroupChange(id) {
  if (!id) return
  groupIdRef.value?.resetField()
  const node: Node = treeGroupRef.value?.getNode(id)
  data.childGroup = node.data.children
}

async function submit() {
  await syncFileFormRef.value?.validate()
  const checkedRows = treeTableRef.value?.getSelectionRows() as any[]

  const { page, pageSize, dataType, ...params_ } = {
    ...toRaw(queryParams)
  }

  if (checkedRows.length == 0 && isObjEmpty(params_)) {
    message.alertWarning('请至少选择一个文件')
    return
  }

  for (const file of checkedRows) {
    if (!file.storagePath) {
      message.alertWarning(`文件路径错误，请检查文件'${file.fileName}'的文件路径`)
      return
    }
    const suffixName = '.' + file.fileName.substring(file.fileName.lastIndexOf('.') + 1)
    const fileTypes_ = fileTypes.reduce((pre, cur: string[]) => pre.concat(cur), [])
    if (!fileTypes_.includes(suffixName)) {
      message.alertWarning(`${suffixName}后缀名的文件不支持`)
      return
    }
  }
  formLoading.value = true

  const idAndQuery =
    checkedRows.length > 0
      ? {
          ids: checkedRows.map((file) => {
            return file.id
          }),
          dataType
        }
      : {
          ids: checkedRows.map((file) => {
            return file.id
          }),
          ...params_,
          dataType
        }

  try {
    await createFromAsset({
      ...toRaw(formData.value),
      pid: formData.value.pid ? formData.value.pid : 0,
      ...idAndQuery,
      deptId: formData.value.deptId,
      sysId: formData.value.sysId
    })
    message.success(t('common.createSuccess'))
    emitter.emit('addFileSuccess')
    reFreshTreeData()
    handleClose()
  } finally {
    formLoading.value = false
  }
}
//判断queryParams中是否有值
function isObjEmpty(obj) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key) && !!obj[key]) {
      return false
    }
  }

  return true
}

function treeNodeClick(row) {
  queryParams.parentId = row.id
  getList()
}

const levelList = ref<Record<string, any>>([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  levelList.value = data
}

const templateList = ref<Record<string, any>>([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({ page: 1, pageSize: 999, type: 0, status: '1' })
  templateList.value = data
}

const deptList = ref<Tree[]>([])
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  deptList.value = data
}

// 分类下拉
const classificationList = ref<any[]>([])
const getClassificationList = async () => {
  const data = await dataClassificationTree({ type: 0 })
  classificationList.value = traverseTree(data)
}

function traverseTree(data) {
  const updatedTree: any[] = []
  for (let i = 0; i < data.length; i++) {
    const node = data[i] // 创建新节点并添加 disable 属性
    if (node.pid == '-1') {
      node.disabled = true
    }
    updatedTree.push(node)
    if (node.children && node.children.length > 0) {
      node.children = traverseTree(node.children) // 递归遍历子节点并更新子树结构
    }
  }
  return updatedTree
}

const systemList = ref()
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}

onMounted(() => {
  if (pageType.value != '1') {
    getList()
  }
  reFreshTreeData()
  getLevelList()
  getTemplateList()
  getDeptList()
  getClassificationList()
  getSystemList()
  setTimeout(() => {
    treeGroupChange(params.pid || '0')
  }, 500)
})

//获取数据源列表
const handleClose = () => {
  router.push({ name: 'DevelopFile' })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 获取文件配置 */
// async function getFileConfig() {
//   const { data } = await FileConfigApi.getFileConfigPage({
//     page: 1,
//     pageSize: 10,
//     name: 'nas'
//   })
//   if (data && data.length > 0) {
//     domain = data[0].config.domain
//     console.log('domain', domain)
//   }
// }

// function pathFormat(path: string) {
//   return `${domain}/admin-api/infra/file/18/get${path.replace('/nas', '')}`
// }
</script>

<style lang="scss" scoped>
.h-full {
  padding: 20px;
}
.row-item {
  padding: 10px 0;

  .col-item {
  }
}

.top-search {
  border-bottom: 1px solid #eee;
}
.bt-wrap {
  margin-top: 30px;
}
.tree-wrap {
  min-height: 600px;
  border-right: 1px solid #eee;
  padding-right: 20px;
}
.table-form {
  border-bottom: 1px solid #eee;
}
</style>
